package com.yanyu.space.common.xxljob;

import com.yanyu.space.common.core.constants.SpaceConstants;
import com.yanyu.space.common.core.properties.XxlJobProperties;
import com.yanyu.space.common.core.yaml.YamlPropertySourceFactory;
import com.yanyu.space.common.xxljob.executor.impl.XxlJobSpringExecutor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:" + SpaceConstants.Properties.XXLJOB_PROP)
@EnableConfigurationProperties(XxlJobProperties.class)
@Slf4j
public class XxljobAutoConfig {

    @Autowired
    private InetUtils inetUtils;

    @Autowired
    private XxlJobProperties xxlJobProperties;

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(xxlJobProperties.getAdmin().getAddresses());
        xxlJobSpringExecutor.setAppname(xxlJobProperties.getExecutor().getAppname());
        xxlJobSpringExecutor.setIp(StringUtils.isNoneBlank(xxlJobProperties.getExecutor().getIp()) ?
                xxlJobProperties.getExecutor().getIp() :
                inetUtils.findFirstNonLoopbackHostInfo().getIpAddress());
        xxlJobSpringExecutor.setPort(xxlJobProperties.getExecutor().getPort());
        xxlJobSpringExecutor.setAccessToken(xxlJobProperties.getAccessToken());
        xxlJobSpringExecutor.setLogPath(xxlJobProperties.getExecutor().getLogPath());
        xxlJobSpringExecutor.setLogRetentionDays(xxlJobProperties.getExecutor().getLogRetentionDays());
        return xxlJobSpringExecutor;
    }

}
